package com.ftg.learn.util.desensitization;



import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * 数据脱敏化序列化处理类
 * @author kangjx
 * @createTime 2022/11/9
 */
public class DesensitizationJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    public DesensitizationJsonSerializer(){}

    private AbstractDesensitization desensitization;


    public DesensitizationJsonSerializer(AbstractDesensitization desensitization) {
        this.desensitization = desensitization;
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(desensitization.serialize(s));
    }


    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        JsonSerializer<?> jsonSerializer = null;
        if (null == beanProperty) {
            jsonSerializer = serializerProvider.findNullValueSerializer(beanProperty);
        }

        if (!Objects.equals(beanProperty.getType().getRawClass(), String.class)){
            jsonSerializer = serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }

        if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
            jsonSerializer = setDesensitization(jsonSerializer, beanProperty);
        }
        return jsonSerializer;
    }

    /**
     * 设置脱敏
     *
     * @param beanProperty
     * @return
     */
    private JsonSerializer<?> setDesensitization(JsonSerializer<?> jsonSerializer, BeanProperty beanProperty) {
        Desensitization desensitization = beanProperty.getAnnotation(Desensitization.class);

        if (desensitization == null) {
            desensitization = beanProperty.getContextAnnotation(Desensitization.class);
        }

        if (desensitization != null) {
            //设置脱敏实例
            try {
                jsonSerializer = new DesensitizationJsonSerializer(desensitization.value().newInstance());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return jsonSerializer;
    }
}